package com.itmck.controller;

import com.alibaba.fastjson.JSON;
import com.itmck.dto.ApiResultResponse;
import com.itmck.pojo.UserVO;
import com.itmck.config.CustomToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;


/**
 * 乍见初欢，久处仍怦然  ---《你若安好便是晴天——林徽因传》
 * <p>
 * Create by M ChangKe 2022/12/28 14:50
 * <p>
 * 用户相关接口
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {


    @PostMapping("/login")
    public ApiResultResponse<String> login(@RequestBody UserVO userVO) {
        log.info("用户登录:{}", JSON.toJSONString(userVO));
        Subject subject = SecurityUtils.getSubject();


        /**
         *
         * 两种方式，创建UsernamePasswordToken 或者自定义创建
         */
//        UsernamePasswordToken token = new UsernamePasswordToken(userVO.getUserName(), userVO.getPassword());
        CustomToken token = new CustomToken(userVO.getUserName(), userVO.getPassword());

        try {
            //当走到这里进行登录的时候实际上交给了com.itmck.config.MyRealm.doGetAuthenticationInfo()方法进行认证操作
            subject.login(token);
        } catch (UnknownAccountException e) {
            //可以不进行抓取直接交给全局异常处理
            return ApiResultResponse.error("用户名错误", "500");
        } catch (IncorrectCredentialsException e) {
            return ApiResultResponse.error("密码错误", "500");
        }
        return ApiResultResponse.ok("登录成功");
    }

    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "退出登录";
    }

    @GetMapping("/no")
    public String unauth() {

        return "未授权没有访问权限";
    }
}